#!/bin/bash

# EnPlatform Assistant MySQL 架构检测和优化脚本
# 支持 AMD64 和 ARM64 架构的自动配置

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检测系统架构
detect_architecture() {
    local arch=$(uname -m)
    local docker_arch=""

    case $arch in
        x86_64)
            docker_arch="linux/amd64"
            ;;
        arm64|aarch64)
            docker_arch="linux/arm64"
            ;;
        *)
            docker_arch="linux/amd64"
            ;;
    esac

    echo $docker_arch
}

# 检查MySQL镜像可用性
check_mysql_image_availability() {
    local platform=$1
    local image="mysql:5.7"

    log_info "检查 MySQL 5.7 镜像在 $platform 平台的可用性..."

    # 对于ARM64，直接返回不可用，使用更好的替代方案
    if [[ "$platform" == "linux/arm64" ]]; then
        log_warning "MySQL 5.7 在 ARM64 上支持有限，将使用更好的替代方案"
        return 1
    fi

    # 尝试拉取镜像
    if docker pull --platform=$platform $image >/dev/null 2>&1; then
        log_success "MySQL 5.7 镜像在 $platform 平台可用"
        return 0
    else
        log_warning "MySQL 5.7 镜像在 $platform 平台不可用"
        return 1
    fi
}

# 为ARM64架构提供替代方案
get_mysql_image_for_arm64() {
    log_info "为 ARM64 架构选择最佳 MySQL 镜像..."

    # ARM64架构的MySQL镜像选项（按优先级排序）
    local images=(
        "mysql:8.0"           # MySQL 8.0 对ARM64支持更好
        "mysql:5.7"           # 尝试原版MySQL 5.7
        "mariadb:10.6"        # MariaDB作为兼容替代
        "mariadb:10.5"        # 更稳定的MariaDB版本
    )

    for image in "${images[@]}"; do
        log_info "测试镜像: $image"
        # 不指定platform，让Docker自动选择
        if docker pull $image >/dev/null 2>&1; then
            log_success "找到可用的 ARM64 MySQL 镜像: $image"
            echo $image
            return 0
        fi
    done

    # 如果都失败了，使用默认的mysql:8.0（通常ARM64支持更好）
    log_warning "使用默认的 mysql:8.0 镜像"
    echo "mysql:8.0"
    return 0
}

# 生成架构特定的docker-compose配置
generate_compose_config() {
    local platform=$1
    local mysql_image=$2
    local config_file="../docker-compose-${platform##*/}.yml"
    
    log_info "生成 $platform 架构的 docker-compose 配置..."
    
    cat > "$config_file" << EOF
# EnPlatform Assistant MySQL Docker Compose 配置
# 架构: $platform
# 生成时间: $(date)

services:
  mysql:
    image: $mysql_image
    platform: $platform
    container_name: enplatform-mysql
    restart: unless-stopped
    
    # 环境变量配置
    environment:
      MYSQL_ROOT_PASSWORD: enplatform123
      MYSQL_DATABASE: enplatform_assistant
      MYSQL_USER: enplatform
      MYSQL_PASSWORD: enplatform123
      MYSQL_ROOT_HOST: '%'
      TZ: Asia/Shanghai
    
    # 端口映射
    ports:
      - "3306:3306"
    
    # 数据卷挂载
    volumes:
      # 数据持久化
      - ./volumes/data:/var/lib/mysql
      # 日志文件
      - ./volumes/logs:/var/log/mysql
      # 配置文件
      - ./mysql.cnf:/etc/mysql/conf.d/custom.cnf:ro
      # 初始化脚本
      - ./init:/docker-entrypoint-initdb.d:ro
    
    # 启动命令参数
    command: >
      --character-set-server=utf8mb4
      --collation-server=utf8mb4_unicode_ci
      --bind-address=0.0.0.0
      --log-error=/var/log/mysql/error.log
      --general-log=1
      --general-log-file=/var/log/mysql/general.log
      --slow-query-log=1
      --slow-query-log-file=/var/log/mysql/slow.log
      --long-query-time=2
      --sql-mode=STRICT_TRANS_TABLES,NO_ZERO_DATE,NO_ZERO_IN_DATE,ERROR_FOR_DIVISION_BY_ZERO
    
    # 健康检查
    healthcheck:
      test: ["CMD", "mysqladmin", "ping", "-h", "localhost", "-u", "root", "-penplatform123"]
      interval: 30s
      timeout: 10s
      retries: 5
      start_period: 30s
    
    # 网络配置
    networks:
      - enplatform-network

# 网络配置
networks:
  enplatform-network:
    driver: bridge
    name: enplatform-network

# 数据卷配置
volumes:
  mysql-data:
    driver: local
  mysql-logs:
    driver: local
EOF

    log_success "配置文件已生成: $config_file"
}

# 更新主配置文件
update_main_compose() {
    local platform=$1
    local mysql_image=$2

    log_info "更新主 docker-compose.yml 配置..."

    # 确定配置文件路径
    local compose_file="docker-compose.yml"
    if [[ -f "../docker-compose.yml" ]]; then
        compose_file="../docker-compose.yml"
    elif [[ -f "docker-compose.yml" ]]; then
        compose_file="docker-compose.yml"
    else
        log_error "找不到 docker-compose.yml 文件"
        return 1
    fi

    # 备份原配置
    cp "$compose_file" "${compose_file}.backup"
    
    # 更新配置
    sed -i.tmp "s|image: mysql:5.7|image: $mysql_image|g" "$compose_file"

    # 根据架构添加或移除platform设置
    if [[ "$platform" == "linux/arm64" ]]; then
        # 为ARM64添加platform设置
        if ! grep -q "platform:" "$compose_file"; then
            # 使用更简单的方法添加platform设置
            sed -i.tmp "/image: $mysql_image/a\\
    platform: $platform" "$compose_file"
        fi
    fi

    # 清理临时文件
    rm -f "${compose_file}.tmp"
    
    log_success "主配置文件已更新"
}

# 创建架构信息文件
create_architecture_info() {
    local platform=$1
    local mysql_image=$2

    # 确定信息文件路径
    local info_file=".architecture-info"
    if [[ -d ".." ]]; then
        info_file="../.architecture-info"
    fi

    cat > "$info_file" << EOF
# EnPlatform Assistant MySQL 架构信息
DETECTED_PLATFORM=$platform
MYSQL_IMAGE=$mysql_image
DETECTION_TIME=$(date)
SYSTEM_ARCH=$(uname -m)
EOF

    log_success "架构信息已保存到 $info_file"
}

# 验证部署
verify_deployment() {
    local mysql_image=$1
    
    log_info "验证 MySQL 部署..."
    
    # 检查镜像是否存在
    if docker images | grep -q "${mysql_image%:*}"; then
        log_success "MySQL 镜像已准备就绪"
    else
        log_warning "MySQL 镜像未找到，将在启动时自动下载"
    fi
    
    # 检查配置文件
    if [[ -f "../docker-compose.yml" ]]; then
        log_success "Docker Compose 配置文件存在"
    else
        log_error "Docker Compose 配置文件不存在"
        return 1
    fi
    
    # 检查初始化脚本
    if [[ -f "../init/01-init-database.sql" ]]; then
        log_success "数据库初始化脚本存在"
    else
        log_warning "数据库初始化脚本不存在"
    fi
    
    log_success "部署验证完成"
}

# 主函数
main() {
    log_info "=== EnPlatform Assistant MySQL 架构优化 ==="

    # 检测架构
    local platform=$(detect_architecture)
    local mysql_image="mysql:5.7"

    log_info "检测到的架构: $platform"

    # 检查MySQL镜像可用性
    if [[ "$platform" == "linux/arm64" ]]; then
        log_info "ARM64 架构检测到，寻找最佳 MySQL 镜像..."
        mysql_image=$(get_mysql_image_for_arm64)
        log_info "选择的 MySQL 镜像: $mysql_image"
    else
        log_info "AMD64 架构，使用 MySQL 5.7"
        check_mysql_image_availability "$platform"
    fi

    # 生成配置
    log_info "生成架构特定配置..."
    generate_compose_config "$platform" "$mysql_image"
    update_main_compose "$platform" "$mysql_image"
    create_architecture_info "$platform" "$mysql_image"

    # 验证部署
    verify_deployment "$mysql_image"

    log_success "=== MySQL 架构优化完成 ==="
    log_info "架构: $platform"
    log_info "MySQL 镜像: $mysql_image"
    log_info "现在可以使用 './manage.sh start' 启动 MySQL 服务"
}

# 执行主函数
main "$@"
